﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Honestysoft.BaseObject;
using System.Data;
using Honestysoft.Financing.Model;
using System.Text;
using System.IO;

namespace Honestysoft.Financing.WebUI.Module.Project.Json
{
    /// <summary>
    /// GetProjectAT 的摘要说明
    /// </summary>
    public class GetProjectAT : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string projectId = context.Request.Params["ID"];
            QueryParameters query = new QueryParameters();
            query.Add("ProjectID", projectId, QueryParameters.OperatorType.Equal);
            OrderParameters order = new OrderParameters();
            order.Add("Code");
            DataTable dtAT = new BaseBusinessLogic<Bu_AuditTable>().GetTable(query, order);
            DataTable dtContract = new BaseBusinessLogic<BD_Contract>().GetTable(query, order);
            dtAT.Columns.Add("ParentID", typeof(string));
            StringBuilder sb = new StringBuilder();
            sb.Append("{");
            sb.AppendFormat("\"total\":{0}", dtContract.Rows.Count + dtAT.Rows.Count);
            sb.Append(",\"rows\":[");
            foreach (DataRow dr in dtContract.Rows)
            {
                sb.Append("{");
                sb.Append(GetSumItem(dr, dtAT));
                sb.Append("},");
            }
            foreach (DataRow dr in dtAT.Rows)
            {
                sb.Append("{");
                sb.Append(GetItem(dr));
                sb.Append("},");
            }
            sb.Remove(sb.Length - 1, 1);
            decimal totalAmount_S = Convert.ToDecimal(dtAT.Compute("Sum(Amount_S)", "ProjectID='" + projectId + "'"));
            decimal totalGiveAmount = Convert.ToDecimal(dtAT.Compute("Sum(GiveAmount)", "ProjectID='" + projectId + "'"));
            decimal loanAmount = new Honestysoft.Financing.BusinessLogic.Project("").GetProjectLoanAmount(projectId, DateTime.Today.Year);
            //项目贷款额度
            sb.Append("],\"footer\":[");
            sb.Append("{");
            sb.AppendFormat("\"Code\":\"合计金额\",\"Amount_S\":\"{0}\",\"GiveAmount\":\"{1}\"",
                string.Format("{0:N}", totalAmount_S), string.Format("{0:N}", totalGiveAmount));
            sb.Append("},{");
            sb.AppendFormat("\"Code\":\"支付比例\",\"Amount_S\":\"{0}\",\"GiveAmount\":\"{1}\"",
                (loanAmount == 0 ? "" : string.Format("{0:P}", totalAmount_S / loanAmount)), (loanAmount == 0 ? "" : string.Format("{0:P}", totalGiveAmount / loanAmount)));
            sb.Append("}]}");
            string data = sb.ToString();
            string fullPath = context.Server.MapPath("~/treegrid_data_test.json");
            if (!System.IO.File.Exists(fullPath))
            {
                System.IO.File.Create(fullPath);
            }
            using (StreamWriter sw = new StreamWriter(fullPath, false, Encoding.Default))
            {
                sw.WriteLine(data);
            }
            context.Response.Write(data);
        }

        private string GetSumItem(DataRow drContract, DataTable dtAll)
        {
            StringBuilder sb = new StringBuilder();
            string contractId = drContract["ID"].ToString();
            bool isRows = (dtAll.Select("ContractID='" + contractId + "'").Length > 0);
            sb.AppendFormat("\"id\":\"{0}\",\"Code\":\"{1}\",\"FirstDate\":\"{2}\",\"Amount_S\":\"{3}\",\"GiveDate\":\"{4}\",\"GiveAmount\":\"{5}\"{6}",
                contractId, drContract["Code"].ToString(),
                string.Format("{0:yyyy/M/d}", dtAll.Compute("Max(FirstDate)", "ContractID='" + contractId + "'")),
                string.Format("{0:N}", dtAll.Compute("Sum(Amount_S)", "ContractID='" + contractId + "'")),
                string.Format("{0:yyyy/M/d}", dtAll.Compute("Max(GiveDate)", "ContractID='" + contractId + "'")),
                string.Format("{0:N}", dtAll.Compute("Sum(GiveAmount)", "ContractID='" + contractId + "'")),
                (isRows ? ",\"state\":\"closed\"" : "")
                );
            return sb.ToString();
        }

        private string GetItem(DataRow dr)
        {
            //"id":1,"name":"All Tasks","begin":"3/4/2010","end":"3/20/2010","progress":60,"iconCls":"icon-ok"
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("\"id\":\"{0}\",\"Code\":\"{1}\",\"FirstDate\":\"{2}\",\"Amount_S\":\"{3}\",\"GiveDate\":\"{4}\",\"GiveAmount\":\"{5}\",\"_parentId\":\"{6}\"",
                dr["ID"].ToString(), dr["Code"].ToString(), string.Format("{0:yyyy/M/d}", dr["FirstDate"]), 
                string.Format("{0:N}", dr["Amount_S"]), string.Format("{0:yyyy/M/d}", dr["GiveDate"]), string.Format("{0:N}", dr["GiveAmount"]),
                dr["ContractID"].ToString());
            return sb.ToString();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}